package com.zjp.dataFormat.aspect;

import com.zjp.dataFormat.annotation.RangeTime;
import com.zjp.dataFormat.pojo.common.CommonTimeQuery;
import com.zjp.dataFormat.service.rangeTime.RangeTimeService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
public class RangeTimeAspect {

    @Autowired
    RangeTimeService rangeTimeService;

    // 配置织入点
    @Pointcut("@annotation(com.zjp.dataFormat.annotation.RangeTime)")
    public void rangeTimePointCut() {
    }

    @Before("rangeTimePointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        handleRangeTime(point);
    }

    private void handleRangeTime(JoinPoint point) {

        System.out.println("---handleRangeTime----");
        // 获得注解
        RangeTime serviceRangeTime = getAnnotationLog(point);
        if (serviceRangeTime == null) {
            return;
        }
        Object[] args = point.getArgs();

        handle(args);
    }

    private void handle(Object[] args) {
        Object arg = args[0];

        CommonTimeQuery commonTimeQuery = arg instanceof CommonTimeQuery ? ((CommonTimeQuery) arg) : null;

        if (Objects.nonNull(commonTimeQuery)) {
            rangeTimeService.handleTimeRange(commonTimeQuery);
            rangeTimeService.log(commonTimeQuery);
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private RangeTime getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(RangeTime.class);
        }
        return null;
    }
}
